<template>
  <div class="account-security">
    <p></p>
    <div class="mem_tit">账户安全</div>
    
    <!-- 修改手机号 -->
    <div class="m_des">
      <el-form :model="phoneForm" :rules="phoneRules" ref="phoneFormRef" label-width="80px">
        <el-form-item label="原手机" prop="oldPhone">
          <el-input v-model="phoneForm.oldPhone" style="width: 180px;" />
        </el-form-item>
        <el-form-item label="新手机" prop="newPhone">
          <el-input v-model="phoneForm.newPhone" style="width: 180px;" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitPhoneForm">确认修改</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 修改邮箱 -->
    <div class="m_des">
      <el-form :model="emailForm" :rules="emailRules" ref="emailFormRef" label-width="80px">
        <el-form-item label="原邮箱" prop="oldEmail">
          <el-input v-model="emailForm.oldEmail" style="width: 180px;" />
        </el-form-item>
        <el-form-item label="新邮箱" prop="newEmail">
          <el-input v-model="emailForm.newEmail" style="width: 180px;" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitEmailForm">确认修改</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 修改密码 -->
    <div class="m_des">
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="80px">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" style="width: 180px;" show-password />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" style="width: 180px;" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" style="width: 180px;" show-password />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitPasswordForm">确认修改</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { updatePhone, updateEmail, updatePassword, checkPassword } from '@/api/userApi'

export default {
  name: 'AccountSecurityComponent',
  data() {
    return {
      // 手机表单数据
      phoneForm: {
        oldPhone: '',
        newPhone: ''
      },
      // 邮箱表单数据
      emailForm: {
        oldEmail: '',
        newEmail: ''
      },
      // 密码表单数据
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      // 手机表单验证规则
      phoneRules: {
        oldPhone: [
          { required: true, message: '请输入原手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        newPhone: [
          { required: true, message: '请输入新手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ]
      },
      // 邮箱表单验证规则
      emailRules: {
        oldEmail: [
          { required: true, message: '请输入原邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        newEmail: [
          { required: true, message: '请输入新邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ]
      },
      // 密码表单验证规则
      passwordRules: {
        oldPassword: [
          { required: true, message: '请输入原密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认新密码', trigger: 'blur' },
          { validator: this.validateConfirmPassword, trigger: 'blur' }
        ]
      },
      // 用户信息
      userInfo: {}
    }
  },
  mounted() {
    // 获取用户信息
    this.fetchUserInfo()
  },
  methods: {
    // 获取用户信息
    fetchUserInfo() {
      const userInfo = localStorage.getItem('userInfo')
      if (userInfo) {
        this.userInfo = JSON.parse(userInfo)
        // 确保用户ID正确设置
        if (this.userInfo.userDetails && this.userInfo.userDetails.id && !this.userInfo.id) {
          this.userInfo.id = this.userInfo.userDetails.id
        }
      }
    },
    
    // 验证确认密码
    validateConfirmPassword(rule, value, callback) {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    },
    
    // 提交手机修改表单
    submitPhoneForm() {
      this.$refs.phoneFormRef.validate((valid) => {
        if (valid) {
          // 检查用户ID是否存在
          if (!this.userInfo.id) {
            this.$message.error('用户信息不完整，请重新登录')
            return
          }
          
          // 调用API进行手机修改
          const params = {
            id: this.userInfo.id,
            mobile: this.phoneForm.newPhone
          }
          
          updatePhone(params).then(response => {
            // 后端返回的是字符串"success"表示成功
            if (response === 'success' || (typeof response === 'object' && response.data === 'success')) {
              this.$message.success('手机号修改成功')
              this.phoneForm = {
                oldPhone: '',
                newPhone: ''
              }
              // 更新本地存储的用户信息
              this.userInfo.mobile = this.phoneForm.newPhone
              localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
            } else {
              this.$message.error(response.message || response || '手机号修改失败')
            }
          }).catch(error => {
            this.$message.error('手机号修改失败: ' + (error.message || '网络错误'))
          })
        } else {
          this.$message.error('请正确填写表单信息')
          return false
        }
      })
    },
    
    // 提交邮箱修改表单
    submitEmailForm() {
      this.$refs.emailFormRef.validate((valid) => {
        if (valid) {
          // 检查用户ID是否存在
          if (!this.userInfo.id) {
            this.$message.error('用户信息不完整，请重新登录')
            return
          }
          
          // 调用API进行邮箱修改
          const params = {
            id: this.userInfo.id,
            email: this.emailForm.newEmail
          }
          
          updateEmail(params).then(response => {
            // 后端返回的是字符串"success"表示成功
            if (response === 'success' || (typeof response === 'object' && response.data === 'success')) {
              this.$message.success('邮箱修改成功')
              this.emailForm = {
                oldEmail: '',
                newEmail: ''
              }
              // 更新本地存储的用户信息
              this.userInfo.email = this.emailForm.newEmail
              localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
            } else {
              this.$message.error(response.message || response || '邮箱修改失败')
            }
          }).catch(error => {
            this.$message.error('邮箱修改失败: ' + (error.message || '网络错误'))
          })
        } else {
          this.$message.error('请正确填写表单信息')
          return false
        }
      })
    },
    
    // 提交密码修改表单
    submitPasswordForm() {
      this.$refs.passwordFormRef.validate((valid) => {
        if (valid) {
          // 检查用户ID是否存在
          if (!this.userInfo.id) {
            this.$message.error('用户信息不完整，请重新登录')
            return
          }
          
          // 首先验证原密码是否正确
          const checkParams = {
            id: this.userInfo.id,
            oldPassword: this.passwordForm.oldPassword
          }
          
          checkPassword(checkParams).then(isValid => {
            if (!isValid) {
              this.$message.error('原密码错误，请重新输入')
              return
            }
            
            // 原密码验证通过，调用API进行密码修改
            const params = {
              id: this.userInfo.id,
              password: this.passwordForm.newPassword
            }
            
            updatePassword(params).then(response => {
              // 后端返回的是字符串"success"表示成功
              if (response === 'success' || (typeof response === 'object' && response.data === 'success')) {
                this.$message.success('密码修改成功')
                this.passwordForm = {
                  oldPassword: '',
                  newPassword: '',
                  confirmPassword: ''
                }
              } else {
                this.$message.error(response.message || response || '密码修改失败')
              }
            }).catch(error => {
              this.$message.error('密码修改失败: ' + (error.message || '网络错误'))
            })
          }).catch(error => {
            this.$message.error('验证原密码失败: ' + (error.message || '网络错误'))
          })
        } else {
          this.$message.error('请正确填写表单信息')
          return false
        }
      })
    }
  }
}
</script>

<style scoped>
.account-security {
  padding: 20px;
}

.mem_tit {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.m_des {
  margin-bottom: 30px;
  padding: 20px;
  background: #f9f9f9;
  border-radius: 4px;
}

.m_des .el-form-item {
  margin-bottom: 20px;
}

.m_des .el-button {
  margin-top: 10px;
}
</style>